package org.anupta.game.utils.others;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.mina.core.buffer.IoBuffer;

public class OutLogger {
	FileOutputStream fos;
    FileChannel writer;
    
    public OutLogger(){
    	try {
            File dossier = new File("Log/Game/"+Config.ID);
            if(!dossier.exists()){
                dossier.mkdirs();
            }
            File log = new File("Log/Game/"+Config.ID+"/" + getDate() + ".log");
            if(log.exists()){
               fos = new FileOutputStream(log);
            }else{
                log.createNewFile();
                fos = new FileOutputStream(log);
            }
            writer = fos.getChannel();
        } catch (IOException ex) {
            Logger.getLogger(ErrorLogger.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    public void println(String message){
        try {
            StringBuilder builder = new StringBuilder().append(getAllDate())
                    .append(' ').append(message).append("\n");
            System.out.println(message);
            writer.write(IoBuffer.wrap(builder.toString().getBytes()).buf());
        } catch (IOException ex) {
            Logger.getLogger(ErrorLogger.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    
    private String getDate(){
        return new StringBuilder(Calendar.getInstance().get(Calendar.DAY_OF_MONTH)+"-"+(Calendar.getInstance().get(Calendar.MONTH)+1)+"-"+Calendar.getInstance().get(Calendar.YEAR)).toString();
    }
    private String getAllDate(){
        return new StringBuilder(new SimpleDateFormat("[dd/MM/yyyy HH:mm]").format(new Date())).toString();
    }

    public void close(){
        try {
            writer.close();
            fos.close();
        } catch (IOException ex) {
            Logger.getLogger(ErrorLogger.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
